% Empirical exercise 2: inflation forecasting 


clear all
warning off
clc


% 0. parameter setup
load emp2.mat
n1 = length(y1);
n2 = length(y2);
XX = {X1,X2};
YY = {y1,y2};
nn = {n1,n2};
WL = 40;
TUN = 0:0.01:5;


% 1. forecasting comparision
tic
for i = 1:2
    X = XX{i};
    y = YY{i};
    n = nn{i};
    N = size(X,2);
    BIAS = zeros(n-WL,6);
    parfor t = 1:n-WL
        % 2. index setup
        IN = t:t+WL-1;
        Xt = X(IN,:);
        yt = y(IN,:);
        Xe = X(t+WL,:);
        ye = y(t+WL,:);
        % 3. estimate weights
        w1 = ones(N,1)/N;   % SIMPLE
        w2 = est_cv(yt,Xt,TUN,1,2);         % LASSO
        w3 = est_cv(yt,Xt,TUN,2,2);         % RIDGE    
        w4 = est_cv(yt,Xt,TUN,3,2);         % L2RELAX no shrinkage
        w5 = est_cv(yt,Xt,TUN,4,2);         % L2RELAX linear shrinkage
        w6 = est_cv(yt,Xt,TUN,5,2);         % L2RELAX nonlinear shrinkage
        % 4. obtain forecast error
        w = [w1 w2 w3 w4 w5 w6];
        W{t} = w;
        f = Xe*w;
        BIAS(t,:) = ye-f;
    end
    SAVE{i} = BIAS;
end
toc


% 5. print results
R = [];
for i = 1:length(SAVE)
    BIAS = SAVE{i};
    R = [R;mean(BIAS.^2); mean(abs(BIAS))];    
end
R = R(:,1:end)./repmat(R(:,1),1,size(R,2));
VN = {'One-year-ahead','Two-year-ahead'};
prt_tab(R([1 3],:),VN,3)
prt_tab(R([2 4],:),VN,3)


% 6. show model weight results
X = {X1,X2};
y = {y1,y2};
TUN = 0.02;
IN = [0.4 0.2 -0.1 -0.3];
VN = {'(a) One-year-ahead','(b) Two-year-ahead'};
figure (2)
for i = 1:length(X)
    w = est_cv(y{i}(1:40),X{i}(1:40,:),TUN,3);
    subplot(1,2,i)
    plotline(IN,sort(w,'descend'))    
    ylim([-0.601 0.601])
    title(VN{i})
end 
 
